package com.hifar.config;

import com.hifar.utils.ToolKit;

import java.sql.Date;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * @author zhuWeiWei
 * @description TODO
 * @date 2025/6/16 15:00
 */
public class DataTypeConverter {

    private static final Map<Class<?>, Function<Object, Object>> CONVERTERS = new HashMap<>();

    static {
        // 日期时间类型转换
        CONVERTERS.put(LocalDate.class, v -> Date.valueOf((LocalDate) v));
        CONVERTERS.put(LocalDateTime.class, v -> Timestamp.valueOf((LocalDateTime) v));
        CONVERTERS.put(Instant.class, v -> Timestamp.from((Instant) v));
        CONVERTERS.put(ZonedDateTime.class, v -> Timestamp.valueOf(((ZonedDateTime) v).toLocalDateTime()));

        // JDK旧日期API
        CONVERTERS.put(java.util.Date.class, v -> new Timestamp(((java.util.Date) v).getTime()));

        // 枚举类型
        CONVERTERS.put(Enum.class, v -> ((Enum<?>) v).name());
    }

    public static Object convertForDatabase(Object value) {
        if (value == null) {
            return null;
        }

        Function<Object, Object> converter = CONVERTERS.get(value.getClass());
        if (converter != null) {
            return converter.apply(value);
        }

        // 检查是否是枚举类型(枚举的父类)
        if (value instanceof Enum) {
            return CONVERTERS.get(Enum.class).apply(value);
        }

        return value;
    }

    public static Map<String, Object> convertMap(Map<String, Object> originalMap) {
        Map<String, Object> convertedMap = new HashMap<>();
        originalMap.forEach((key, value) -> {
            convertedMap.put(ToolKit.camelToSnake(key), convertForDatabase(value));
        });
        return convertedMap;
    }
}
